﻿using System.Net;

namespace GT
{
    public static partial class Extensions
    {
        public static IPAddress GetNetworkAddress(this IPAddress source, int cidr)
        {
            return source.GetNetworkAddress(cidr.FromCidr());
        }

        public static IPAddress GetNetworkAddress(this IPAddress source, IPAddress netmask)
        {
            byte[] addr = source.GetAddressBytes();
            byte[] mask = netmask.GetAddressBytes();
            return new IPAddress(addr.And(mask));
        }

        public static IPAddress GetBroadcastAddress(this IPAddress source, int cidr)
        {
            return source.GetBroadcastAddress(cidr.FromCidr());
        }

        public static IPAddress GetBroadcastAddress(this IPAddress source, IPAddress netmask)
        {
            byte[] addr = source.GetAddressBytes();
            byte[] mask = netmask.GetAddressBytes();
            return new IPAddress(addr.Nor(mask));
        }

        public static bool IsPrivate(this IPAddress ip)
        {
            return 
                (
                    ip.GetNetworkAddress(8).Equals(IPAddress.Parse("10.0.0.0")) ||
                    ip.GetNetworkAddress(12).Equals(IPAddress.Parse("172.16.0.0")) ||
                    ip.GetNetworkAddress(16).Equals(IPAddress.Parse("169.254.0.0")) ||
                    ip.GetNetworkAddress(16).Equals(IPAddress.Parse("192.168.0.0")) ||
                    ip.GetNetworkAddress(7).Equals(IPAddress.Parse("fc00::"))
                );
        }
    }
}
